import React, { useRef, useState, useEffect } from "react";
import styles from "./index.less";
import Box from "./components/Box";
import Swiper from "./components/Swiper";

import Sortable from "/Users/renwang/Desktop/Sortable/modular/sortable.esm.js";
import BoxDrag from "./components/BoxDrag";
import BoxDrop from "./components/BoxDrop";
import { nanoid } from "nanoid";

import { uuid } from "./util";
const components = { Box: Box, Swiper: Swiper };
const componentList = [
  {
    id: uuid(),
    type: "Box",
    name: "图片组件",
    bgColor: "red",
    h: 100,
    w: 100,
    config: {
      url: "https://t7.baidu.com/it/u=2537132411,3912460994&fm=193&f=GIF",
      form: [{ inputType: "input", title: "图片地址：", value: "" }],
    },
  },
  {
    id: uuid(),
    type: "Swiper",
    name: "横滑图片",
    bgColor: "blue",
    h: 100,
    w: 100,
  },
];
function Index() {
  const leftRef = useRef(null);
  const centerRef = useRef(null);
  const [list, setList] = useState([]);
  const [config, setConfig] = useState({});
  const [current, setCurrent] = useState(-1);

  let newAddedComponent = useRef(null);
  const removeNode = (node) => {
    if (node.parentElement !== null) node.parentElement.removeChild(node);
  };
  useEffect(() => {
    const s1 = Sortable.create(leftRef.current, {
      group: {
        name: "BOX",
        pull: "clone",
        put: false,
      },
      animation: 150,
      sort: false,
    });
    const s2 = Sortable.create(centerRef.current, {
      group: {
        name: "BOX",
        put: ["BOX"],
      },
      sort: true,
      animation: 150,
      onAdd: (evt) => {
        evt.item.style.display = "none";
        newAddedComponent.current = {
          id: evt.item.dataset.id,
          index: evt.newIndex,
          oldIndex: evt.item.dataset.index,
          dom: evt.item,
        };
      },
      store: {
        set: function (sortable) {
          if (newAddedComponent.current) {
            const { id, index, oldIndex, dom } = newAddedComponent.current;
            removeNode(dom);
            let _list = [...list];
            let item = componentList[oldIndex];
            item = {
              ...item,
              cid: ["BOX", "-", nanoid(12)].join(""),
            };
            if (index == 0) {
              _list.unshift(item);
            } else if (index === list.length) {
              _list.push(item);
            } else {
              _list.splice(index, 0, item);
            }
            setList([..._list]);
            newAddedComponent.current = null;
          } else {
            let order = sortable.toArray();
            let newList = [];
            order.forEach((id) => {
              list.forEach((item) => {
                if (id === item?.cid) {
                  newList.push(item);
                }
              });
            });
            setList([...newList]);
          }
        },
      },
    });
    return () => {
      s2.destroy();
      s1.destroy();
    };
  }, [list, newAddedComponent, uuid]);

  const onRemove = (index) => {
    console.log(index);
    list.splice(index, 1);
    setList([...list]);
  };
  const onItem = (index) => {
    setCurrent(index);
    setConfig({ ...list[index]["config"] });
  };
  const inputChange = (e, index) => {
    config["form"][index]["value"] = e.target.value;
    config["url"] = e.target.value;

    list[current]["config"] = config;
    setConfig({ ...config });
    setList([...list]);
  };
  return (
    <div className={styles.canvasView}>
      <div ref={leftRef} className={styles.left}>
        {componentList.map((item, index) => {
          return (
            <BoxDrag index={index} item={item} type="BOX" key={item?.id} />
          );
        })}
      </div>
      <div className={styles.showView}>
        <div ref={centerRef} className={styles.center}>
          {list.map((item, index) => {
            const Cmp = components[item.type];
            return (
              <BoxDrop
                onItem={() => onItem(index)}
                onRemove={() => onRemove(index)}
                item={item}
                type="BOX"
                key={item?.cid}
                isActive={index === current}
              >
                <Cmp item={item} />
              </BoxDrop>
            );
          })}
        </div>
      </div>

      <div className={styles.right}>
        {config?.form &&
          config.form.map((item, index) => {
            return (
              <div key={item.cid}>
                <label>
                  {item.title}
                  <input
                    onChange={(e) => inputChange(e, index)}
                    value={item.value}
                  />
                </label>
              </div>
            );
          })}
      </div>
    </div>
  );
}

export default Index;
